/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package me.whily.hee.model.service;

import java.sql.SQLException;
import javax.persistence.EntityManager;

/**
 * 
 * @author wanghy
 * @since 2015-5-22 16:00:49
 */
public abstract class AbstractService {

    public EntityManager em;

    public AbstractService() {
        em = EMSingleton.getInstance();
    }

    public void executeSql(String sql) throws SQLException {
        beginTransaction(em);
        em.createNativeQuery(sql).executeUpdate();
        commitTransaction(em);
        closeEntityManager(em);
    }

    public void closeEntityManager(EntityManager em) {
        em.close();
    }

    public void rollbackTransacrion(EntityManager em) throws SQLException {
        if (em != null) {
            em.getTransaction().rollback();
        }
    }

    public void commitTransaction(EntityManager em) throws SQLException {
        em.getTransaction().commit();
    }

    public void beginTransaction(EntityManager em) throws SQLException {
        em.getTransaction().begin();
    }
}
